package com.chookss.tiku

import androidx.lifecycle.LiveData
import androidx.lifecycle.MutableLiveData
import com.chookss.tiku.entity.LiveResult
import com.chookss.tiku.entity.Subject
import com.chookss.tiku.entity.SubjectAnswer
import com.chookss.tiku.response.SubjectAnswerList
import com.chookss.tools.httpForm
import com.johnrambo.ktea.base.BaseViewModel

/**
 * Company:
 * Project:
 * Author: liuhaoge
 * Date: 2020/12/28
 * Note: 题目选项列表加载类
 */
abstract class SubjectAnswerViewModel : BaseViewModel() {
    //1001 选择题
    //1002 多选题
    //1003 判断题

    //题目对应的选项列表缓存
    val subjectAnswerCache = mutableMapOf<String, List<SubjectAnswer>>()

    //下载题目列表
    abstract fun getSubject(index: Int): LiveData<LiveResult<Subject>>

    //下载选项列表
    fun getSubjectAnswer(
            subjectCode: String
    ) : LiveData<LiveResult<List<SubjectAnswer>>> {
        var liveResult = MutableLiveData<LiveResult<List<SubjectAnswer>>>()
        var cache = subjectAnswerCache[subjectCode]
        if (cache != null) {
            liveResult.postValue(LiveResult(cache))
            return liveResult
        }

        jobs + httpForm<SubjectAnswerList.Response> {
            url = "api/subject/getSubjectAnswer"
            params = mutableMapOf("subjectCode" to subjectCode)
            onSuccess = {
                var list: List<SubjectAnswer>? = it.data
                subjectAnswerCache[subjectCode] = list ?: emptyList()
                liveResult.postValue(LiveResult(list))
            }
            onError = {
                liveResult.postValue(LiveResult(Error(it)))
            }
        }
        return liveResult
    }

}